﻿using CBS.APP;
using CBS.Common.Office;
using CBS.Model.ManageModel;
using CBS.Model.UIModel;
using CBS.Model.ViewModel;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace CBS.Desktop.SystemStatement
{
    /// <summary>
    /// CourseBillingStatement.xaml 的交互逻辑
    /// </summary>
    public partial class CourseBillingStatement : Window
    {
        private Pagination pager = new() { rows = 10, page = 1, sidx = nameof(CourseBillingStatementViewModel.StudentId), sord = "desc" };
        public CourseBillingStatement()
        {
            InitializeComponent();

            dg_Data.Columns.Add(new DataGridTextColumn() { Header = "序号" });
            dg_Data.Columns.Add(new DataGridTextColumn() { Header = "学生姓名" });
            dg_Data.Columns.Add(new DataGridTextColumn() { Header = "上期余款" });
            dg_Data.Columns.Add(new DataGridTextColumn() { Header = "缴费总金额" });
            dg_Data.Columns.Add(new DataGridTextColumn() { Header = "课程" });
            dg_Data.Columns.Add(new DataGridTextColumn() { Header = "本期余款" });
            dg_Data.Columns.Add(new DataGridTextColumn() { Header = "备注" });

            LoadCondation();
        }

        private async void LoadCondation()
        {
            btn_Search.IsEnabled = false;
            btn_Export.IsEnabled = false;

            // 加载 ComboBox 数据
            await LoadDataAsync();

            // 查询 Grid 数据
            //FlushGrid();

            btn_Search.IsEnabled = true;
            btn_Export.IsEnabled = true;
        }

        private async Task LoadDataAsync()
        {
            // 使用 Task.WhenAll 等待所有 ComboBox 数据加载完成
            var tasks = new List<Task>
            {
                BindSemester(),
                BindClass(),
            };

            await Task.WhenAll(tasks);
        }

        private async void FlushGrid()
        {
            try
            {
                //序号，学生姓名，上期余款，缴费总金额，[课程]，本期余款，备注
                btn_Search.IsEnabled = false;
                btn_Export.IsEnabled = false;
                int semesterId = ((SemesterSelectModel)cb_Semester.SelectedItem).SemesterId;
                int classPlanId = ((CoursePlanSelectModel)cb_Class.SelectedItem).CoursePlanId; // int.Parse(cb_Class.SelectedValue.ToString()); ;
                string studentName = tb_Student.Text.Trim();


                dg_Data.Columns.Clear();

                dg_Data.Columns.Add(new DataGridTextColumn() { Header = "序号", Binding = new Binding("RowNumber") });
                dg_Data.Columns.Add(new DataGridTextColumn() { Header = "学生姓名", Binding = new Binding("StudentName") });
                dg_Data.Columns.Add(new DataGridTextColumn() { Header = "上期余款", Binding = new Binding("StudentName") });
                dg_Data.Columns.Add(new DataGridTextColumn() { Header = "缴费总金额", Binding = new Binding("StudentName") });
                //课程
                var courseList = CoursePlanApp.GetSemesterSetCourseName(semesterId);
                foreach (var item in courseList)
                {
                    dg_Data.Columns.Add(new DataGridTextColumn() { Header = item.CourseId, Binding = new Binding(item.CourseName) });
                }
                dg_Data.Columns.Add(new DataGridTextColumn() { Header = "本期余款", Binding = new Binding("StudentName") });
                dg_Data.Columns.Add(new DataGridTextColumn() { Header = "备注", Binding = new Binding("StudentName") });

                var data = await Task.Run(() => SystemStatementApp.GetCourseBillingStatementList(pager, semesterId, studentName, courseList));

                this.Dispatcher.Invoke(new Action(() =>
                {
                    pg_DataList.MaxPageCount = pager.total;
                    dg_Data.ItemsSource = data;
                    btn_Search.IsEnabled = true;
                    btn_Export.IsEnabled = true;
                }));
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "发生错误！", MessageBoxButton.OK, MessageBoxImage.Error);
                btn_Search.IsEnabled = true;
                btn_Export.IsEnabled = true;
            }

        }

        public async Task BindSemester()
        {
            try
            {
                btn_Search.IsEnabled = false;
                btn_Export.IsEnabled = false;
                var list = await Task.Run(() => SemesterApp.GetSelectList());


                this.Dispatcher.Invoke(() =>
                {
                    cb_Semester.ItemsSource = list;
                    cb_Semester.SelectedIndex = 0;
                    btn_Search.IsEnabled = true;
                    btn_Export.IsEnabled = true;

                });
                
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "发生错误！", MessageBoxButton.OK, MessageBoxImage.Error);
                btn_Search.IsEnabled = true;
                btn_Export.IsEnabled = true;
            }

        }

        public async Task BindClass()
        {
            try
            {
                btn_Search.IsEnabled = false;
                btn_Export.IsEnabled = false;
                //int semesterId = ((SemesterSelectModel)cb_Semester.SelectedItem).SemesterId;
                var list = await Task.Run(() => ClassApp.GetSelectList());

                list.Insert(0, new() { ClassId = 0, ClassName = "全部" });

                this.Dispatcher.Invoke(new Action(() =>
                {
                    cb_Semester.ItemsSource = list;
                    cb_Semester.SelectedIndex = 0;

                    
                }));
                FlushGrid();
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "发生错误！", MessageBoxButton.OK, MessageBoxImage.Error);
                btn_Search.IsEnabled = true;
                btn_Export.IsEnabled = true;
            }

        }

        private void btn_Search_Click(object sender, RoutedEventArgs e)
        {
            pager.page = 1;
            pg_DataList.PageIndex = 1;
            FlushGrid();
        }

        private void btn_Export_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                btn_Search.IsEnabled = false;
                btn_Export.IsEnabled = false;
                Mouse.OverrideCursor = Cursors.Wait;

                OpenFolderDialog dialog = new OpenFolderDialog();
                var result = dialog.ShowDialog();
                if (result == true)
                {
                    ExportToFile(dialog.FolderName);
                    btn_Search.IsEnabled = true;
                    btn_Export.IsEnabled = true;
                    Mouse.OverrideCursor = null;
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "发生错误！", MessageBoxButton.OK, MessageBoxImage.Error);
                btn_Search.IsEnabled = true;
                btn_Export.IsEnabled = true;
                Mouse.OverrideCursor = null;
            }
        }

        private async void ExportToFile(string filePath)
        {
            try
            {
                int semesterId = ((SemesterSelectModel)cb_Semester.SelectedItem).SemesterId;
                int classPlanId = int.Parse(cb_Class.SelectedValue.ToString()); ;
                string studentName = tb_Student.Text.Trim();
                //课程
                var courseList = CoursePlanApp.GetSemesterSetCourseName(semesterId);
                var data = await Task.Run(() => SystemStatementApp.GetCourseBillingStatementDataTable(semesterId, studentName, courseList));

                string fileName = $"{filePath}\\学生签到详情报表-{new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds()}.xlsx";
                List<ImportField> fields = new()
                {
                    new(){ Name = "SemesterName", DisplayName = "学期名称" },
                    new(){ Name = "ClassPlanName", DisplayName = "班级名称" },
                    new(){ Name = "ClassPlanName", DisplayName = "班级名称" },
                    new(){ Name = "TeacherName", DisplayName = "讲课老师" },
                    new(){ Name = "StudentName", DisplayName = "学生姓名" },
                    new(){ Name = "StartTime", DisplayName = "开始时间" },
                    new(){ Name = "IsTaster", DisplayName = "是否是试听课" },
                };

                string[] nameArray = fields.Select(t => t.Name).ToArray();
                foreach (DataColumn col in data.Columns)
                {
                    var field = fields.FirstOrDefault(t => t.Name == col.ColumnName);
                    if (field == null)
                    {
                        data.Columns.Remove(col);
                        continue;
                    }

                    col.Caption = field.DisplayName;
                }

                ExcelHelper.TableToExcelForXLSX(data, $"{filePath}\\{fileName}");

                btn_Search.IsEnabled = true;
                btn_Export.IsEnabled = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "发生错误！", MessageBoxButton.OK, MessageBoxImage.Error);
                btn_Search.IsEnabled = true;
                btn_Export.IsEnabled = true;
            }

        }

        private void pg_DataList_PageUpdated(object sender, HandyControl.Data.FunctionEventArgs<int> e)
        {
            pager.page = e.Info;
            FlushGrid();
        }
    }
}
